App({
  globalData: {
    userInfo: null,
    baseUrl: 'http://localhost:8000/api/v1'
  },
  onLaunch() {
    console.log('应用启动')
    // 获取本地存储的token
    const token = wx.getStorageSync('access_token');
    if (token) {
      console.log('发现已保存的token，开始验证')
      // 验证token是否有效
      this.checkToken(token);
    } else {
      console.log('未找到token')
    }
  },
  checkToken(token) {
    console.log('开始验证token')
    wx.request({
      url: `${this.globalData.baseUrl}/users/profiles/me/`,
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        console.log('token验证结果:', res)
        if (res.statusCode === 200) {
          console.log('token有效，保存用户信息')
          this.globalData.userInfo = res.data;
        } else if (res.statusCode === 401) {
          console.log('token已过期，尝试刷新')
          // token过期，尝试使用refresh token
          const refreshToken = wx.getStorageSync('refresh_token');
          if (refreshToken) {
            this.refreshToken(refreshToken);
          } else {
            console.log('没有refresh token，需要重新登录')
            this.clearTokenAndRedirect();
          }
        } else {
          console.error('验证失败，状态码:', res.statusCode);
          this.clearTokenAndRedirect();
        }
      },
      fail: (error) => {
        console.error('验证请求失败:', error);
        this.clearTokenAndRedirect();
      }
    });
  },
  
  refreshToken(refreshToken) {
    console.log('开始刷新token')
    wx.request({
      url: `${this.globalData.baseUrl}/token/refresh/`,
      method: 'POST',
      data: {
        refresh: refreshToken
      },
      success: (res) => {
        console.log('刷新token结果:', res)
        if (res.statusCode === 200) {
          console.log('token刷新成功')
          wx.setStorageSync('access_token', res.data.access);
          this.checkToken(res.data.access);
        } else {
          console.error('刷新失败，状态码:', res.statusCode)
          this.clearTokenAndRedirect();
        }
      },
      fail: (error) => {
        console.error('刷新请求失败:', error)
        this.clearTokenAndRedirect();
      }
    });
  },

  clearTokenAndRedirect() {
    console.log('清除token并重定向到登录页')
    wx.removeStorageSync('access_token');
    wx.removeStorageSync('refresh_token');
    wx.redirectTo({
      url: '/pages/login/login',
      success: () => console.log('重定向成功'),
      fail: (error) => console.error('重定向失败:', error)
    });
  }
})